package demo.api.ding;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import demo.engine.template.MarkdownDemo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 钉钉消息发送
 *
 * @author junying.han
 */
public class DingSendUtils {
    /**
     * test-alert 群
     */
    public static final String TEST_DING_URL = "https://oapi.dingtalk.com/robot/send?access_token=0d09ba4a6ed98246941768036084fd19b1ef5f65517f669bd7c90360e87eb655";
    protected static final Logger logger = LoggerFactory.getLogger(DingSendUtils.class);

    /**
     * 环境信息
     */
    private static String env = "开发环境";
    private DingSendUtils() {
        super();
    }

    /**
     * 发送消息，如果消息过大，则会拆分
     *
     * @param msgList
     * @param mobiles
     * @param dingUrl
     */
    public static void sendChatRobotTextMsgList(List<StringBuilder> msgList, Collection<String> mobiles, String dingUrl) {
        if (msgList == null || msgList.isEmpty()) {
            return;
        }
        StringBuilder stringBuilder = new StringBuilder(String.format("[%s]%n", env));
        for (StringBuilder msg : msgList) {
            if (msg == null || msg.length() <= 0) {
                continue;
            }
            stringBuilder.append(msg).append(" \n\n");
            // 如果超过钉钉消息限制，则分多次发送
            if (stringBuilder.length() >= DingUtils.MSG_LIMIT - 256) {
                sendTextMsg(stringBuilder, mobiles, dingUrl, false);
                stringBuilder = new StringBuilder();
            }
        }
        if (stringBuilder.length() > 0) {
            sendTextMsg(stringBuilder, mobiles, dingUrl, false);
        }
    }

    /**
     * 发送消息，如果消息过大，则会拆分
     *
     * @param title
     * @param msgList
     * @param dingUrl
     * @param mobiles
     * @param atAll
     */
    public static void sendMarkdownMsg(String title, List<String> msgList, String dingUrl, Set<String> mobiles, boolean atAll) {
        if (msgList == null || msgList.isEmpty()) {
            return;
        }
        dingUrl = StringUtils.isBlank(dingUrl) ? TEST_DING_URL : dingUrl;
        StringBuilder reducedMsg = new StringBuilder();
        for (String msg : msgList) {
            if (msg == null || msg.isEmpty()) {
                continue;
            }
            reducedMsg.append(msg).append(MarkdownDemo.mdLine());
            // 如果超过钉钉消息限制，则分多次发送
            if (reducedMsg.length() >= DingUtils.MSG_LIMIT - 256) {
                sendMarkdownMsg(title, reducedMsg, mobiles, dingUrl, atAll);
                reducedMsg = new StringBuilder();
            }
        }
        if (reducedMsg.length() > 0) {
            sendMarkdownMsg(title, reducedMsg, mobiles, dingUrl, atAll);
        }
    }

    /**
     * 发送机器人文本消息
     *
     * @param msg
     * @param mobiles
     * @param robotUrl
     * @return
     */
    public static boolean sendTextMsg(String msg, Collection<String> mobiles, String robotUrl) {
        return sendTextMsg(new StringBuilder(msg), mobiles, robotUrl, false);
    }

    /**
     * 发送机器人文本消息
     *
     * @param msg
     * @param mobiles
     * @param robotUrl
     * @return
     */
    public static boolean sendTextMsg(StringBuilder msg, Collection<String> mobiles, String robotUrl, boolean atAll) {
        if (msg == null || msg.length() == 0) {
            logger.warn("send {} failed,msg is empty", robotUrl);
            return false;
        }
        try {
            OapiRobotSendResponse response = DingTalkApiUtils.sendText(msg.toString(), robotUrl, mobiles, atAll);
            boolean success = response.isSuccess();
            if (!success) {
                logger.error("send msg failed, response:{}", JSON.toJSONString(response));
            }
            return success;
        } catch (Exception e) {
            logger.error("httpPost error:{}", e.getMessage());
            return false;
        }
    }

    /**
     * 发送机器人markdown消息
     *
     * @param title
     * @param msg
     * @param mobiles
     * @param robotUrl
     * @param atAll
     * @return
     */
    public static boolean sendMarkdownMsg(String title, StringBuilder msg, Collection<String> mobiles, String robotUrl, boolean atAll) {
        if (msg == null || msg.length() == 0) {
            logger.warn("msg is empty");
            return false;
        }
        robotUrl = StringUtils.isBlank(robotUrl) ? TEST_DING_URL : robotUrl;
        try {
            if (!atAll && mobiles != null && !mobiles.isEmpty()) {
                String atMobiles = mobiles.stream().distinct().map(m -> "@" + m).collect(Collectors.joining(" "));
                msg.append("\n\n").append(atMobiles).append("\n\n");
            }
            OapiRobotSendResponse response = DingTalkApiUtils.sendMarkdown(title, msg.toString(), robotUrl, mobiles, atAll);
            boolean success = response.isSuccess();
            if (!success) {
                logger.error("send msg failed, response:{}", JSON.toJSONString(response));
            }
            return success;
        } catch (Exception e) {
            logger.error("sendMarkdown failed, title:{} , robot:{}", title, robotUrl, e);
            return false;
        }
    }

    /**
     * 发送机器人ActionCard消息
     *
     * @param title
     * @param msg
     * @param mobiles
     * @param robotUrl
     * @param atAll
     * @param buttonList
     * @return
     */
    public static boolean sendActionCardMsg(String title, StringBuilder msg,
                                            Collection<String> mobiles, String robotUrl,
                                            boolean atAll, List<OapiRobotSendRequest.Btns> buttonList) {
        if (msg == null || msg.length() == 0) {
            logger.warn("msg is empty");
            return false;
        }
        try {
            if (!atAll && mobiles != null && !mobiles.isEmpty()) {
                String atMobiles = mobiles.stream().distinct().map(m -> "@" + m).collect(Collectors.joining(" "));
                msg.append("\n\n").append(atMobiles).append("\n\n");
            }
            OapiRobotSendResponse response = DingTalkApiUtils.sendActionCard(title, msg.toString(), robotUrl, mobiles, atAll, buttonList);
            boolean success = response.isSuccess();
            if (!success) {
                logger.error("send msg failed, response:{}", JSON.toJSONString(response));
            }
            return success;
        } catch (Exception e) {
            logger.error("sendMarkdown failed, title:{} , robot:{}", title, robotUrl, e);
            return false;
        }
    }

}
